package utilities.service;
import java.util.Date;

import utilities.BDSQLiteHelper;
import utilities.Preferencias;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;

public class InsertarSms {
	Context context;
	final int ENVIADOS = 2;
	Preferencias pref;
	Long fechaTope;
	
	public InsertarSms(Context context){
		this.context = context;
		pref = new Preferencias(context);
		getMensajes();
	}
	
	private void getMensajes() {
		fechaTope = Long.parseLong(pref.getPref(Preferencias.FECHA_CREACION_PLAN, ""));
		Object[] obj = null;
		Uri uriSMSURI = Uri.parse("content://sms/");
	    Cursor cur = context.getContentResolver().query(uriSMSURI, null, "date >= "+fechaTope+" AND TYPE = "+ENVIADOS, null,"date DESC");
	    String destinatario,nombre="",compania;
	    Date fecha;
	    int longitud,_id,idc=0;
	    
	    BDSQLiteHelper usdbh = new BDSQLiteHelper(context, "DB_PEI", null, 1);
		SQLiteDatabase dbsms=null;
		
		
		try{
			
		
		dbsms = usdbh.getReadableDatabase();
		Cursor csms;
		
	    while (cur.moveToNext()) {
	    	obj = null;
	        destinatario = cur.getString(cur.getColumnIndex("address"));
	        _id = cur.getInt(cur.getColumnIndex("_id"));
//	        nombre = getContact(cur.getString(cur.getColumnIndex("address")));
	        compania = Compania(cur.getString(cur.getColumnIndex("address")).toString());
	        fecha = new Date(Long.valueOf(cur.getString( cur.getColumnIndex("date"))));
	        longitud = cur.getString(cur.getColumnIndex("body")).toString().length();
	        obj = getContact(cur.getString(cur.getColumnIndex("address")));
			if(obj != null){//En la posicion 0 vendra el nombre
				nombre = (String)obj[0];
				idc = (Integer)obj[1];
			}
			
			//si el sms ya existe no la metemos a la tabla, si retorna algo, saltamos al registro
			csms = dbsms.query("PEI_MENSAJE", new String[]{"ID_MENSAJE"}, "ID_MENSAJE = "+_id, null, null, null, null);
			if(csms.moveToFirst()) continue; 
				
			dbsms.execSQL("INSERT INTO PEI_MENSAJE(ID_MENSAJE," +
					"NUM_DESTINATARIO," +
					"NOM_DESTINATARIO," +
					"FECHA," +
					"PROVEEDOR_DESTINO," +
					"LONG_MENSAJE," +
					"ID_CONTACTO," +
					"EST_ESTADO) " +
					"VALUES ('"+_id+"','"+
					destinatario+"','"+
					nombre+"','"+
					fecha.getTime()+"','"+
					compania+"','"+
					longitud+"','" +
					idc+"',1)");
	          
			calcular(longitud,compania);
	    	  	          
	      }
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			dbsms.close();
		}
	}
	
	public Object[] getContact(String number) {
		Object[] obj = new Object[]{null,null};
		int idc;
    	String[] columns = new String[] {
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER,
				ContactsContract.Contacts.PHOTO_ID,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID				};
    	Uri uriContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		Cursor cur = context.getContentResolver().query(
				uriContacts, 
				columns,
				Phone.NUMBER + " like '%"+number+"'", 
				null, 
				null
		);

		if (cur.moveToFirst()) {
            obj[0] = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            idc = cur.getInt(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            obj[1] = idc;
            return obj;
        }
        return null;
	}
	
	public String Compania(String number) {
		int n;
		String num = number.replaceFirst("-", "");
		num = num.replaceFirst("503", "");
		num = num.replaceFirst("\\+", "");
		if(num.length()!=8 || num.charAt(0)!='7'){
			return "Desconocido";
		}
        num = num.substring(0,4);
        n = Integer.parseInt(num);
        
        if(((n>=7000)&&(n<=7099))||                  
             ((n>=7600)&&(n<=7669))||
             ((n>=7687)&&(n<=7690))||
             ((n>=7740)&&(n<=7759))||
             ((n>=7805)&&(n<=7809))||
             ((n>=7840)&&(n<=7844))||
             ((n>=7850)&&(n<=7869))||
             ((n>=7950)&&(n<=7969))||
             ((n>=7985)&&(n<=7989))){
                        return "CLARO";           
        }
                                                
        if(((n>=7300)&&(n<=7399))||                                        
                ((n>=7400)&&(n<=7449))||                                                                           
                ((n>=7460)&&(n<=7469))||
                ((n>=7695)&&(n<=7698))||
                ((n>=7760)&&(n<=7779))||
                ((n>=7970)&&(n<=7979))){
                 return "DIGICEL";                         
        }

        if(((n>=7100)&&(n<=7199))||
                  ((n>=7450)&&(n<=7459))||
                  ((n>=7691)&&(n<=7694))||
              ((n>=7700)&&(n<=7719))||
              ((n>=7780)&&(n<=7784))||
              ((n>=7790)&&(n<=7794))||
              ((n>=7810)&&(n<=7839))||
              ((n>=7845)&&(n<=7849))||
              ((n>=7990)&&(n<=7999))){
                return "MOVISTAR";
        }
        
        if(((n>=7200)&&(n<=7299))||
             ((n>=7470)&&(n<=7499))||
             ((n>=7500)&&(n<=7599))||                        
             ((n>=7670)&&(n<=7679))||
             ((n>=7680)&&(n<=7683))||
             ((n>=7720)&&(n<=7739))||
             ((n>=7785)&&(n<=7789))||
             ((n>=7795)&&(n<=7799))||
             ((n>=7870)&&(n<=7899))||
             ((n>=7900)&&(n<=7949))){
                        return "TIGO";

                }
        return "Desconocido";
	}
	
	private void calcular(int longitud,String comp){
		double tarifaExt=0,tarifaLoc=0;
		double totalConsumido = Double.parseDouble(pref.getPref(Preferencias.CONSUMO_TOTAL, "0"));
		String tplan="",proveedorSer="";
		
		double lonSms=longitud,limiteSms=160;
		double cantSms = Math.ceil(lonSms/limiteSms);
		int smsInc=0,totalsms = Integer.parseInt(pref.getPref(Preferencias.MENSAJES_ENVIADOS, "0"));;
		BDSQLiteHelper usdbh = new BDSQLiteHelper(context, "DB_PEI", null, 1);
		SQLiteDatabase db = null;
		try{
			db = usdbh.getReadableDatabase();
			Cursor c_plan = db.query("PEI_PLAN", new String[] {"COSTO_MSJ_EXTERNO","COSTO_MSJ_LOCAL","TIPO_PLAN","PROVEEDOR_SERVICIOS","MENSAJES_INCLUIDOS"}, null, null, null, null, null);
			if(c_plan.moveToFirst()){
				tarifaExt = Double.parseDouble(c_plan.getString(0));
				tarifaLoc =  Double.parseDouble(c_plan.getString(1));
				tplan = c_plan.getString(2);
				proveedorSer = c_plan.getString(3);
				smsInc = c_plan.getInt(4);
			}
			int tmpTotal =totalsms; 
			totalsms+=(int)cantSms;
			if(tplan.equalsIgnoreCase("Postpago")){//Si es postpago, tiene minutosIncluidos
				int cantACobrar = totalsms-smsInc; 
				if(cantACobrar>0 && tmpTotal<smsInc){
					if(proveedorSer.equalsIgnoreCase(comp))//tarifa entre misma compania
						totalConsumido = totalConsumido+cantACobrar*tarifaLoc;
					else//tarifa enter difernte compania
						totalConsumido = totalConsumido+cantACobrar*tarifaExt;
				}
				else if(tmpTotal>=smsInc){
					if(proveedorSer.equalsIgnoreCase(comp))//tarifa entre misma compania
						totalConsumido = totalConsumido+cantSms*tarifaLoc;
					else//tarifa enter difernte compania
						totalConsumido = totalConsumido+cantSms*tarifaExt;
				}
			}
			else{
				if(proveedorSer.equalsIgnoreCase(comp))//tarifa entre misma compania
					totalConsumido = totalConsumido+cantSms*tarifaLoc;
				else//tarifa enter difernte compania
					totalConsumido = totalConsumido+cantSms*tarifaExt;
			}
			float tmp = (float) 0.00;
			tmp = (float) totalConsumido;
			pref.setPref(Preferencias.CONSUMO_TOTAL, tmp+"");
			pref.setPref(Preferencias.MENSAJES_ENVIADOS, totalsms+"");
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			db.close();
		}
		
	}

}
